package com.lagou.dao;

import com.lagou.domain.Student;
import com.lagou.util.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import javax.sql.DataSource;
import java.sql.SQLException;

public class MysqlDao {
    //检查用户名是否存在的方法
    public boolean daoCheck(String name, String password) throws SQLException {
        //1.获取连接池DataSource对象
        DataSource dataSource = DruidUtils.getDataSource();

        //2.使用DBUtils
        QueryRunner qr = new QueryRunner(dataSource);

        Object[] params = {name,password};
        //3.判断用户名和密码是否正确
        Long id = (Long)qr.query("select id from teacher where username = ? and password = ?",new ScalarHandler(),params);

        //4.如果查到了 count >=1
        return id >= 1;
    }

    public boolean addUser(Student stu) throws SQLException {
        QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());

        //向数据库中插入一个对象
        String sql = "insert into student values(?,?,?,?,?)";
        Object[] param = {null,stu.getUsername(),stu.getSex(),stu.getBirth()};
        int i = qr.update(sql, param);  //i表示受影响的函数
        return i>=1;          //返回true表示插入成功，false表示插入失败
    }
}